define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'echarts'], function ($, undefined, Backend, Table, Form, echarts) {

    var Controller = {
        costReport: function () {
            // 初始化日期选择器
            $('.datetimepicker').datetimepicker({
                format: 'yyyy-mm-dd',
                locale: 'zh-cn',
                autoclose: true
            });

            // 初始化图表
            var trendChart = echarts.init(document.getElementById('cost-trend-chart'));
            var structureChart = echarts.init(document.getElementById('cost-structure-chart'));

            // 加载数据
            function loadData() {
                var startDate = $('#start_date').val();
                var endDate = $('#end_date').val();

                Backend.api.ajax({
                    url: 'scanwork/bi/costReport',
                    data: {
                        start_date: startDate,
                        end_date: endDate
                    }
                }, function (data, ret) {
                    if (ret.code === 1) {
                        updateSummary(data.summary);
                        updateTrendChart(data.trend);
                        updateStructureChart(data.structure);
                    } else {
                        Backend.api.toastr.error(ret.msg);
                    }
                });
            }

            // 更新汇总数据
            function updateSummary(data) {
                $('#material-cost').text('¥' + (data.total_material_cost || 0).toFixed(2));
                $('#labor-cost').text('¥' + (data.total_labor_cost || 0).toFixed(2));
                $('#overhead-cost').text('¥' + (data.total_overhead_cost || 0).toFixed(2));
                $('#total-cost').text('¥' + (data.total_cost || 0).toFixed(2));
                $('#total-revenue').text('¥' + (data.total_revenue || 0).toFixed(2));
                $('#total-profit').text('¥' + (data.total_profit || 0).toFixed(2));
                $('#avg-profit-rate').text((data.avg_profit_rate || 0).toFixed(2) + '%');
            }

            // 更新成本趋势图
            function updateTrendChart(data) {
                var dates = data.map(function(item) { return item.date; });
                var materialCost = data.map(function(item) { return item.material_cost; });
                var laborCost = data.map(function(item) { return item.labor_cost; });
                var overheadCost = data.map(function(item) { return item.overhead_cost; });
                var totalCost = data.map(function(item) { return item.total_cost; });

                var option = {
                    tooltip: {
                        trigger: 'axis'
                    },
                    legend: {
                        data: ['物料成本', '人工成本', '制造费用', '总成本']
                    },
                    xAxis: {
                        type: 'category',
                        data: dates
                    },
                    yAxis: {
                        type: 'value',
                        name: '金额(元)'
                    },
                    series: [
                        {
                            name: '物料成本',
                            type: 'line',
                            data: materialCost,
                            smooth: true
                        },
                        {
                            name: '人工成本',
                            type: 'line',
                            data: laborCost,
                            smooth: true
                        },
                        {
                            name: '制造费用',
                            type: 'line',
                            data: overheadCost,
                            smooth: true
                        },
                        {
                            name: '总成本',
                            type: 'line',
                            data: totalCost,
                            smooth: true,
                            lineStyle: {
                                width: 3
                            }
                        }
                    ]
                };
                trendChart.setOption(option);
            }

            // 更新成本结构图
            function updateStructureChart(data) {
                var option = {
                    tooltip: {
                        trigger: 'item',
                        formatter: '{a} <br/>{b}: {c} ({d}%)'
                    },
                    legend: {
                        orient: 'vertical',
                        left: 'left'
                    },
                    series: [
                        {
                            name: '成本构成',
                            type: 'pie',
                            radius: ['40%', '70%'],
                            avoidLabelOverlap: false,
                            label: {
                                show: true,
                                formatter: '{b}: {d}%'
                            },
                            data: [
                                {value: data.material_cost || 0, name: '物料成本'},
                                {value: data.labor_cost || 0, name: '人工成本'},
                                {value: data.overhead_cost || 0, name: '制造费用'}
                            ]
                        }
                    ]
                };
                structureChart.setOption(option);
            }

            // 查询按钮事件
            $('.btn-search').on('click', function() {
                loadData();
            });

            // 初始加载
            loadData();

            // 窗口大小改变时重新调整图表
            $(window).on('resize', function() {
                trendChart.resize();
                structureChart.resize();
            });
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});
